require('dotenv').config()
// 导入数据库操作模块
const db = require('../../db')
// MARK 部门管理

// MARK GET / company / department	查询部门列表
exports.getList = (req, res) => {
  const query = 'SELECT * FROM department'

  db.query(query, (err, results) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10001, message: '获取部门列表失败', error: err.message })
    }

    if (results.length === 0) {
      return res.json({
        success: true,
        code: 10000,
        data: [],
        message: '获取组织架构数据成功'
      })
    }

    // 提取所有的 managerId
    const managerIds = results.map(department => department.managerId).filter(id => id !== null);

    // 如果没有 managerId，则直接返回结果
    if (managerIds.length === 0) {
      const data = results.map(department => ({
        id: department.id,
        pid: department.pid,
        name: department.name,
        code: department.code,
        managerId: department.managerId,
        managerName: null, // 没有 managerId 时设置为 null
        introduce: department.introduce,
        createTime: department.create_time
      }))

      return res.json({
        success: true,
        code: 10000,
        data: data,
        message: '获取组织架构数据成功'
      })
    }

    // 查询 employee 表获取 managerName
    const employeeQuery = 'SELECT id, username FROM employee WHERE id IN (?)'
    db.query(employeeQuery, [managerIds], (err, employeeResults) => {
      if (err) {
        return res.status(500).json({ success: false, code: 10001, message: '获取员工信息失败', error: err.message })
      }

      // 创建一个映射，将 managerId 映射到 username
      const managerNameMap = employeeResults.reduce((acc, employee) => {
        acc[employee.id] = employee.username
        return acc
      }, {})

      // 合并数据
      const data = results.map(department => ({
        id: department.id,
        pid: department.pid,
        name: department.name,
        code: department.code,
        managerId: department.managerId,
        managerName: managerNameMap[department.managerId] || null, // 如果没有对应的 managerName，则设置为 null
        introduce: department.introduce,
        createTime: department.create_time
      }))

      res.json({
        success: true,
        code: 10000,
        data: data,
        message: '获取组织架构数据成功'
      })
    })
  })
}
// MARK POST / company / department	新增部门
exports.addNew = (req, res) => {
  const { code, introduce, managerId, name, pid } = req.body
  // MARK 限制部门层级
  // if (pid > 7) {
  //   return res.status(400).json({ success: false, code: 10010, message: '部门层级过深' })
  // }
  // 验证输入数据
  if (!code || !name || !pid) {
    return res.status(400).json({ success: false, code: 10002, message: '缺少必要的字段' })
  }

  if (code.length < 1 || code.length > 50) {
    return res.status(400).json({ success: false, code: 10003, message: '部门编码长度应在1-50个字符之间' })
  }

  if (name.length < 1 || name.length > 50) {
    return res.status(400).json({ success: false, code: 10004, message: '部门名称长度应在1-50个字符之间' })
  }

  if (introduce && introduce.length > 300) {
    return res.status(400).json({ success: false, code: 10005, message: '部门介绍长度不能超过300个字符' })
  }

  // 检查部门编码是否重复
  const checkCodeQuery = 'SELECT * FROM department WHERE code = ?'
  db.query(checkCodeQuery, [code], (err, results) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10006, message: '检查部门编码失败', error: err.message })
    }

    if (results.length > 0) {
      return res.status(400).json({ success: false, code: 10007, message: '部门编码已存在' })
    }

    // 检查同级部门名称是否重复
    const checkNameQuery = 'SELECT * FROM department WHERE name = ? AND pid = ?'
    db.query(checkNameQuery, [name, pid], (err, results) => {
      if (err) {
        return res.status(500).json({ success: false, code: 10008, message: '检查部门名称失败', error: err.message })
      }

      if (results.length > 0) {
        return res.status(400).json({ success: false, code: 10009, message: '同级部门名称已存在' })
      }
      // 生成创建时间
      const createTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
      // 插入新部门
      const insertQuery = 'INSERT INTO department (code, introduce, managerId, name, pid,createTime) VALUES (?,?, ?, ?, ?, ?)'
      db.query(insertQuery, [code, introduce, managerId, name, pid, createTime], (err, result) => {
        if (err) {
          return res.status(500).json({ success: false, code: 10010, message: '新增部门失败', error: err.message })
        }

        res.json({
          success: true,
          code: 10000,
          data: { id: result.insertId },
          message: '新增部门成功'
        })
      })
    })
  })
}
// MARK GET / company / department / { id }	获取部门详情
exports.getById = (req, res) => {
  const { id } = req.params

  const query = 'SELECT * FROM department WHERE id = ?'
  db.query(query, [id], (err, results) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10011, message: '获取部门详情失败', error: err.message })
    }

    if (results.length === 0) {
      return res.status(404).json({ success: false, code: 10012, message: '部门不存在' })
    }

    const department = results[0]
    res.json({
      success: true,
      code: 10000,
      data: {
        id: department.id,
        pid: department.pid,
        name: department.name,
        code: department.code,
        managerId: department.managerId,
        introduce: department.introduce,
        createTime: department.create_time
      },
      message: '获取部门详情成功'
    })
  })
}
// MARK PUT / company / department / { id }	修改部门详情
exports.putById = (req, res) => {
  const { id } = req.params
  const { code, introduce, managerId, name, pid } = req.body
  // console.log("PUT / company / department / { id }	", req.body)
  // MARK 维护初始数据
  if (id >= 1 && id <= 7) {
    return res.status(200).json({ success: false, code: 10023, message: '初始数据不可操作' })
  }
  // 验证输入数据
  if (!code || !name || pid == null) {
    console.log(`code:${code},name:${name},pid:${pid}`)
    return res.status(400).json({ success: false, code: 10013, message: '缺少必要的字段' })
  }

  if (code.length < 1 || code.length > 50) {
    return res.status(400).json({ success: false, code: 10014, message: '部门编码长度应在1-50个字符之间' })
  }

  if (name.length < 1 || name.length > 50) {
    return res.status(400).json({ success: false, code: 10015, message: '部门名称长度应在1-50个字符之间' })
  }

  if (introduce && introduce.length > 300) {
    return res.status(400).json({ success: false, code: 10016, message: '部门介绍长度不能超过300个字符' })
  }

  // 检查部门是否存在
  const checkDepartmentQuery = 'SELECT * FROM department WHERE id = ?'
  db.query(checkDepartmentQuery, [id], (err, results) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10017, message: '检查部门失败', error: err.message })
    }

    if (results.length === 0) {
      return res.status(404).json({ success: false, code: 10018, message: '部门不存在' })
    }

    // 检查部门编码是否重复
    const checkCodeQuery = 'SELECT * FROM department WHERE code = ? AND id != ?'
    db.query(checkCodeQuery, [code, id], (err, results) => {
      if (err) {
        return res.status(500).json({ success: false, code: 10019, message: '检查部门编码失败', error: err.message })
      }

      if (results.length > 0) {
        return res.status(400).json({ success: false, code: 10020, message: '部门编码已存在' })
      }

      // 检查同级部门名称是否重复
      const checkNameQuery = 'SELECT * FROM department WHERE name = ? AND pid = ? AND id != ?'
      db.query(checkNameQuery, [name, pid, id], (err, results) => {
        if (err) {
          return res.status(500).json({ success: false, code: 10021, message: '检查部门名称失败', error: err.message })
        }

        if (results.length > 0) {
          return res.status(400).json({ success: false, code: 10022, message: '同级部门名称已存在' })
        }

        // 更新部门信息
        const updateQuery = 'UPDATE department SET code = ?, introduce = ?, managerId = ?, name = ?, pid = ? WHERE id = ?'
        db.query(updateQuery, [code, introduce, managerId, name, pid, id], (err, result) => {
          if (err) {
            return res.status(500).json({ success: false, code: 10023, message: '更新部门失败', error: err.message })
          }

          res.json({
            success: true,
            code: 10000,
            data: { id: id },
            message: '更新部门成功'
          })
        })
      })
    })
  })
}
// MARK DELETE / company / department / { id }	删除部门
exports.delById = (req, res) => {
  // 从 params 获取部门 ID
  const { id } = req.params;

  // 维护初始数据，ID 为 1-7 的部门不可删除
  if (id >= 1 && id <= 7) {
    return res.status(200).json({ success: false, code: 10023, message: '初始数据不可操作' });
  }

  // 检查部门是否存在
  const checkDepartmentQuery = 'SELECT * FROM department WHERE id = ?';
  db.query(checkDepartmentQuery, [id], (err, results) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10024, message: '检查部门失败', error: err.message });
    }

    if (results.length === 0) {
      return res.status(404).json({ success: false, code: 10025, message: '部门不存在' });
    }

    // 删除目标部门及其所有子部门
    const deleteQuery = 'DELETE FROM department WHERE id = ? OR pid = ?';
    db.query(deleteQuery, [id, id], (err, result) => {
      if (err) {
        return res.status(500).json({ success: false, code: 10026, message: '删除部门失败', error: err.message });
      }

      res.json({
        success: true,
        code: 10000,
        data: null,
        message: '删除部门及其子部门成功'
      });
    });
  });
};

/**
 * 
 // MARK DELETE / company / department / { id }	删除部门
exports.delById = (req, res) => {
  // path参数 从params获取
  const { id } = req.params
  // MARK 维护初始数据
  if (id >= 1 && id <= 7) {
    return res.status(200).json({ success: false, code: 10023, message: '初始数据不可操作' })
  }
  // 检查部门是否存在
  const checkDepartmentQuery = 'SELECT * FROM department WHERE id = ?'
  db.query(checkDepartmentQuery, [id], (err, results) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10024, message: '检查部门失败', error: err.message })
    }

    if (results.length === 0) {
      return res.status(404).json({ success: false, code: 10025, message: '部门不存在' })
    }

    // 删除部门
    const deleteQuery = 'DELETE FROM department WHERE id = ?'
    db.query(deleteQuery, [id], (err, result) => {
      if (err) {
        return res.status(500).json({ success: false, code: 10026, message: '删除部门失败', error: err.message })
      }

      res.json({
        success: true,
        code: 10000,
        data: null,
        message: '删除部门成功'
      })
    })
  })
}
 */